package com.fgs.common.utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Typeface;
import android.text.Layout;
import android.text.StaticLayout;
import android.text.TextPaint;

import java.util.List;

/**
 * @author fgs
 * @date 2020/10/16
 * @description
 **/
public class WaterMarkerUtils {
    /**
     * 设置水印图片在左上角
     *
     * @param context     上下文
     * @param src
     * @param watermark
     * @param paddingLeft
     * @param paddingTop
     * @return
     */
    public static Bitmap createWaterMaskLeftTop(Context context, Bitmap src, Bitmap watermark, int paddingLeft, int paddingTop) {
        return createWaterMaskBitmap(src, watermark,
                dp2px(context, paddingLeft), dp2px(context, paddingTop));
    }

    private static Bitmap createWaterMaskBitmap(Bitmap src, Bitmap watermark, int paddingLeft, int paddingTop) {
        if (src == null) {
            return null;
        }
        int width = src.getWidth();
        int height = src.getHeight();
        //创建一个bitmap
        Bitmap newb = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);// 创建一个新的和SRC长度宽度一样的位图
        //将该图片作为画布
        Canvas canvas = new Canvas(newb);
        //在画布 0，0坐标上开始绘制原始图片
        canvas.drawBitmap(src, 0, 0, null);
        //在画布上绘制水印图片
        canvas.drawBitmap(watermark, paddingLeft, paddingTop, null);
        // 保存
        canvas.save();
        // 存储
        canvas.restore();
        return newb;
    }

    /**
     * 设置水印图片在右下角
     *
     * @param context       上下文
     * @param src
     * @param watermark
     * @param paddingRight
     * @param paddingBottom
     * @return
     */
    public static Bitmap createWaterMaskRightBottom(Context context, Bitmap src, Bitmap watermark, int paddingRight, int paddingBottom) {
        return createWaterMaskBitmap(src, watermark,
                src.getWidth() - watermark.getWidth() - dp2px(context, paddingRight),
                src.getHeight() - watermark.getHeight() - dp2px(context, paddingBottom));
    }

    /**
     * 设置水印图片到右上角
     *
     * @param context
     * @param src
     * @param watermark
     * @param paddingRight
     * @param paddingTop
     * @return
     */
    public static Bitmap createWaterMaskRightTop(Context context, Bitmap src, Bitmap watermark, int paddingRight, int paddingTop) {
        return createWaterMaskBitmap(src, watermark,
                src.getWidth() - watermark.getWidth() - dp2px(context, paddingRight),
                dp2px(context, paddingTop));
    }

    /**
     * 设置水印图片到左下角
     *
     * @param context
     * @param src
     * @param watermark
     * @param paddingLeft
     * @param paddingBottom
     * @return
     */
    public static Bitmap createWaterMaskLeftBottom(Context context, Bitmap src, Bitmap watermark, int paddingLeft, int paddingBottom) {
        return createWaterMaskBitmap(src, watermark, dp2px(context, paddingLeft),
                src.getHeight() - watermark.getHeight() - dp2px(context, paddingBottom));
    }

    /**
     * 设置水印图片到中间
     *
     * @param src
     * @param watermark
     * @return
     */
    public static Bitmap createWaterMaskCenter(Bitmap src, Bitmap watermark) {
        return createWaterMaskBitmap(src, watermark,
                (src.getWidth() - watermark.getWidth()) / 2,
                (src.getHeight() - watermark.getHeight()) / 2);
    }

    /**
     * 给图片添加文字到左上角
     *
     * @param bitmap
     * @param text
     * @return
     */
    public static Bitmap drawTextToLeftTop(Bitmap bitmap, String text, int color) {
        try {
            if (null == bitmap) {
                return null;
            }

            int srcWidth = bitmap.getWidth();
            int srcHeight = bitmap.getHeight();

            int unitHeight = srcHeight > srcWidth ? srcWidth / 30 : srcHeight / 25;
            int padding = unitHeight;
            int textSize = unitHeight;


            // 设置画笔
            TextPaint textPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG | Paint.DEV_KERN_TEXT_FLAG);
            textPaint.setTextSize(textSize);// 字体大小
            textPaint.setAntiAlias(true);
            textPaint.setTypeface(Typeface.DEFAULT);// 采用默认的宽度
            textPaint.setColor(color);// 采用的颜色v

            Rect bounds = new Rect();
            textPaint.getTextBounds(text, 0, text.length(), bounds);
            int iconWidth = bounds.height();//图片宽度
            int maxTextWidth = srcWidth - padding * 3 - iconWidth;//最大文字宽度
            //文字处理
            StaticLayout layout = new StaticLayout(text, textPaint, maxTextWidth, Layout.Alignment.ALIGN_NORMAL,
                    1.0f, 0.0f, true); // 确定换行
            return drawTextToBitmap(bitmap, layout,
                    padding,
                    padding);
        } catch (Exception e) {
            e.printStackTrace();
            return bitmap;
        }
    }

    /**
     * 绘制文字到右下角
     *
     * @param bitmap
     * @param text
     * @param color
     * @return
     */
    public static Bitmap drawTextToRightBottom(Bitmap bitmap, String text, int color) {
        try {
            if (null == bitmap) {
                return null;
            }

            int srcWidth = bitmap.getWidth();
            int srcHeight = bitmap.getHeight();

            int unitHeight = srcHeight > srcWidth ? srcWidth / 30 : srcHeight / 25;
            int padding = unitHeight;
            int textSize = unitHeight;


            // 设置画笔
            TextPaint textPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG | Paint.DEV_KERN_TEXT_FLAG);
            textPaint.setTextSize(textSize);// 字体大小
            textPaint.setTypeface(Typeface.DEFAULT);// 采用默认的宽度
            textPaint.setColor(color);// 采用的颜色v

            Rect bounds = new Rect();
            textPaint.getTextBounds(text, 0, text.length(), bounds);
            int iconWidth = bounds.height();//图片宽度
            int maxTextWidth = srcWidth - padding * 3 - iconWidth;//最大文字宽度
            //文字处理
            StaticLayout layout = new StaticLayout(text, textPaint, maxTextWidth, Layout.Alignment.ALIGN_OPPOSITE,
                    1.0f, 0.0f, true); // 确定换行
            String layoutWidth = layout.getWidth() + "";
            String width = srcWidth - layout.getWidth() - padding + "";
            LogUtil.print("layoutWidth", layoutWidth);
            LogUtil.print("width", width);

            return drawTextToBitmap(bitmap, layout,
                    srcWidth - layout.getWidth() - padding,
                    srcHeight - layout.getHeight() - padding);
        } catch (Exception e) {
            e.printStackTrace();
            return bitmap;
        }
    }

    /**
     * 绘制文字到右上方
     *
     * @param bitmap
     * @param text
     * @param color
     * @return
     */
    public static Bitmap drawTextToRightTop(Bitmap bitmap, String text, int color) {

        try {
            if (null == bitmap) {
                return null;
            }

            int srcWidth = bitmap.getWidth();
            int srcHeight = bitmap.getHeight();

            int unitHeight = srcHeight > srcWidth ? srcWidth / 30 : srcHeight / 25;
            int padding = unitHeight;
            int textSize = unitHeight;


            // 设置画笔
            TextPaint textPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG | Paint.DEV_KERN_TEXT_FLAG);
            textPaint.setTextSize(textSize);// 字体大小
            textPaint.setTypeface(Typeface.DEFAULT);// 采用默认的宽度
            textPaint.setColor(color);// 采用的颜色v

            Rect bounds = new Rect();
            textPaint.getTextBounds(text, 0, text.length(), bounds);
            int iconWidth = bounds.height();//图片宽度
            int maxTextWidth = srcWidth - padding * 3 - iconWidth;//最大文字宽度
            //文字处理
            StaticLayout layout = new StaticLayout(text, textPaint, maxTextWidth, Layout.Alignment.ALIGN_OPPOSITE,
                    1.0f, 0.0f, true); // 确定换行
            return drawTextToBitmap(bitmap, layout,
                    srcWidth - layout.getWidth() - padding,
                    padding);
        } catch (Exception e) {
            e.printStackTrace();
            return bitmap;
        }
    }


    /**
     * 绘制文字到中间
     *
     * @param bitmap
     * @param text
     * @param color
     * @return
     */
    public static Bitmap drawTextToCenter(Bitmap bitmap, String text, int color) {
        try {
            if (null == bitmap) {
                return null;
            }

            int srcWidth = bitmap.getWidth();
            int srcHeight = bitmap.getHeight();

            int unitHeight = srcHeight > srcWidth ? srcWidth / 30 : srcHeight / 25;
            int padding = unitHeight;
            int textSize = unitHeight;


            // 设置画笔
            TextPaint textPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG | Paint.DEV_KERN_TEXT_FLAG);
            textPaint.setTextSize(textSize);// 字体大小
            textPaint.setTypeface(Typeface.DEFAULT);// 采用默认的宽度
            textPaint.setColor(color);// 采用的颜色v

            Rect bounds = new Rect();
            textPaint.getTextBounds(text, 0, text.length(), bounds);
            int iconWidth = bounds.height();//图片宽度
            int maxTextWidth = srcWidth - padding * 3 - iconWidth;//最大文字宽度
            //文字处理
            StaticLayout layout = new StaticLayout(text, textPaint, maxTextWidth, Layout.Alignment.ALIGN_CENTER,
                    1.0f, 0.0f, true); // 确定换行
            return drawTextToBitmap(bitmap, layout,
                    (srcWidth - layout.getWidth()) / 2,
                    (srcHeight - layout.getHeight()) / 2);
        } catch (Exception e) {
            e.printStackTrace();
            return bitmap;
        }
    }

    /**
     * 绘制文字到左下方
     *
     * @param bitmap
     * @param text
     * @param color
     * @return
     */
    public static Bitmap drawTextToLeftBottom(Bitmap bitmap, String text, int color) {
        try {
            if (null == bitmap) {
                return null;
            }

            int srcWidth = bitmap.getWidth();
            int srcHeight = bitmap.getHeight();

//            int unitHeight = srcHeight > srcWidth ? srcWidth / 30 : srcHeight / 25;
            int unitHeight = srcHeight > srcWidth ? srcWidth / 27 : srcHeight / 23;
            int padding = unitHeight;
            int textSize = unitHeight;


            // 设置画笔
            TextPaint textPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG | Paint.DEV_KERN_TEXT_FLAG);
            textPaint.setTextSize(textSize);// 字体大小
            textPaint.setAntiAlias(true);
            textPaint.setTypeface(Typeface.DEFAULT);// 采用默认的宽度
            textPaint.setColor(color);// 采用的颜色v

            Rect bounds = new Rect();
            textPaint.getTextBounds(text, 0, text.length(), bounds);
            int iconWidth = bounds.height();//图片宽度
            int maxTextWidth = srcWidth - padding * 3 - iconWidth;//最大文字宽度
            //文字处理
            StaticLayout layout = new StaticLayout(text, textPaint, maxTextWidth, Layout.Alignment.ALIGN_NORMAL,
                    1.0f, 0.0f, true); // 确定换行
            return drawTextToBitmap(bitmap, layout,
                    padding,
                    srcHeight - layout.getHeight() - padding / 2);
        } catch (Exception e) {
            e.printStackTrace();
            return bitmap;
        }

    }

    //图片上绘制文字
    private static Bitmap drawTextToBitmap(Bitmap bitmap, StaticLayout layout, int paddingLeft, int paddingTop) {
        //将该图片作为画布
        Bitmap newBitmap = bitmap;
        try {
            if (null == bitmap) {
                return null;
            }
            //创建一个bitmap
            if (!newBitmap.isMutable()) {
                newBitmap = bitmap.copy(bitmap.getConfig(), true);
            }
            Canvas canvas = new Canvas(newBitmap);

            //绘制文字
            canvas.translate(paddingLeft, paddingTop); // 设定画布位置
            layout.draw(canvas); // 绘制水印
            return newBitmap;
        } catch (Exception e) {
            e.printStackTrace();
            return newBitmap;
        }

    }

    /**
     * 缩放图片
     *
     * @param src
     * @param w
     * @param h
     * @return
     */
    public static Bitmap scaleWithWH(Bitmap src, double w, double h) {
        if (w == 0 || h == 0 || src == null) {
            return src;
        } else {
            // 记录src的宽高
            int width = src.getWidth();
            int height = src.getHeight();
            // 创建一个matrix容器
            Matrix matrix = new Matrix();
            // 计算缩放比例
            float scaleWidth = (float) (w / width);
            float scaleHeight = (float) (h / height);
            // 开始缩放
            matrix.postScale(scaleWidth, scaleHeight);
            // 创建缩放后的图片
            return Bitmap.createBitmap(src, 0, 0, width, height, matrix, true);
        }
    }

    /**
     * dip转pix
     *
     * @param context
     * @param dp
     * @return
     */
    public static int dp2px(Context context, float dp) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dp * scale + 0.5f);
    }


    /**
     * 左下角添加水印（多行，图标 + 文字）
     * 参考资料：
     * Android 对Canvas的translate方法总结    https://blog.csdn.net/u013681739/article/details/49588549
     *
     * @param photo
     */
    public static Bitmap addWaterMark(Context context, Bitmap photo, List<String> textList, List<Integer> iconIdList, boolean isShowIcon) {
        Bitmap newBitmap = photo;
        try {
            if (null == photo) {
                return null;
            }

            int srcWidth = photo.getWidth();
            int srcHeight = photo.getHeight();

            //Resources resources = context.getResources();
            //float scale = resources.getDisplayMetrics().density;
            int unitHeight = srcHeight > srcWidth ? srcWidth / 30 : srcHeight / 25;
            int padding = unitHeight;
            int marginLeft = padding;
            int marginBottom = padding;
            int textSize = unitHeight;

            //创建一个bitmap
            if (!newBitmap.isMutable()) {
                newBitmap = photo.copy(photo.getConfig(), true);
            }
            //将该图片作为画布
            Canvas canvas = new Canvas(newBitmap);

            // 设置画笔
            TextPaint textPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG | Paint.DEV_KERN_TEXT_FLAG);
            textPaint.setTextSize(textSize);// 字体大小
            textPaint.setTypeface(Typeface.DEFAULT);// 采用默认的宽度
            textPaint.setColor(Color.WHITE);// 采用的颜色v

            Rect bounds = new Rect();
            String gText = "hello world!";
            textPaint.getTextBounds(gText, 0, gText.length(), bounds);

            int iconWidth = bounds.height();//图片宽度
            int maxTextWidth = srcWidth - padding * 3 - iconWidth;//最大文字宽度

            for (int i = textList.size() - 1; i >= 0; i--) {
                String text = textList.get(i);
                int iconId = iconIdList.get(i);

                canvas.save();//锁画布(为了保存之前的画布状态)

                //文字处理
                StaticLayout layout = new StaticLayout(text, textPaint, maxTextWidth, Layout.Alignment.ALIGN_NORMAL,
                        1.0f, 0.0f, true); // 确定换行
                //在画布上绘制水印图片
                if (isShowIcon) {
                    Bitmap watermark = BitmapFactory.decodeResource(context.getResources(), iconId);
                    int iconHeight = iconWidth * ((watermark.getHeight() * 1000) / watermark.getWidth()) / 1000;//维持图片宽高比例，也可以简单粗暴 iconHeight = iconWidth;
                    //图片相对文字位置居中
                    RectF rectF = new RectF(marginLeft, srcHeight - marginBottom - layout.getHeight() / 2 - iconHeight / 2
                            , marginLeft + iconWidth, srcHeight - marginBottom - layout.getHeight() / 2 + iconHeight / 2);
                    canvas.drawBitmap(watermark, null, rectF, null);//限定图片显示范围
                }

                //绘制文字
                canvas.translate(isShowIcon ? marginLeft + iconWidth + padding : marginLeft, srcHeight - layout.getHeight() - marginBottom); // 设定画布位置
                layout.draw(canvas); // 绘制水印

                //marginBottom 更新
                marginBottom = marginBottom + (padding + layout.getHeight());

                canvas.restore();//把当前画布返回（调整）到上一个save()状态之前
            }

            // 保存
            canvas.save();
            // 存储
            canvas.restore();

        } catch (Exception e) {
            e.printStackTrace();
            return newBitmap;
        }
        return newBitmap;
    }


}
